//
//  HomeController.m
//  项目
//
//  Created by 焦钟培 on 14-12-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "HomeController.h"
#import "ConnectModel.h"
#import "HomePoltController.h"
#import "WebColor.h"
#import "Reachability.h"

#define kBlueColor [UIColor colorWithRed:129/255.0 green: 198/255.0 blue: 221/255.0 alpha: 1.0]

@interface HomeController ()

@end

@implementation HomeController
- (void)dealloc
{
    [_iamg release];
    [_coArray release];
    [_buttonArray release];
    [_backImage release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.buttonArray = [NSMutableArray array];
        self.coArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 60)];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:25];
    label.text = @"渊虹";
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _backImage.image = [UIImage imageNamed:@"5.png"];
    [self.view addSubview:_backImage];
    [_backImage release];
    [self startF];
    self.iamg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shua.png"]];
    _iamg.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 - 64);
    [label release];
    [self.view addSubview:_iamg];

    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.RepeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeForwards;
    [_iamg.layer addAnimation:rotationAnimation forKey:@"rotation"];
}
#warning 解析
- (BOOL)judgeConnected
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    NetworkStatus status = [reach currentReachabilityStatus];
    switch (status) {
        case NotReachable:
        {
            return NO;
        }
            break;
        case ReachableViaWiFi:
        {
            return YES;
        }
            break;
        case ReachableViaWWAN:
        {
            return YES;
        }
            break;
        default:
            break;
    }
}


- (void)alertF
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常请重试" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    [_iamg removeFromSuperview];
    [alert show];
    [alert release];
}


- (void)startF
{
    BOOL judge = [self judgeConnected];
    if (!judge) {
        [NSTimer scheduledTimerWithTimeInterval:0.0f target:self selector:@selector(alertF) userInfo:nil repeats:NO];
        return;
    }
    [_coArray removeAllObjects];
    [_buttonArray removeAllObjects];
    [ConnectModel connectModelWithUrlStr:@"http://api.pianke.me/read/recommend%20HTTP/1.1" parmaters:nil block:^(NSData *data) {
        [_iamg removeFromSuperview];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dics = [dic objectForKey:@"data"];
        [_buttonArray addObjectsFromArray:[dics objectForKey:@"list"]];
        [_coArray addObjectsFromArray:_buttonArray];
        [self createImage];
    }];
    
}
- (void)createImage
{
    if (!self.judge) {
        [self createButton];
        _judge = YES;
    }
    
    NSInteger x = arc4random()%(NSInteger)self.view.frame.size.width;
    NSInteger last = arc4random()%(NSInteger)self.view.frame.size.width;
    NSString *picStr = @"";
    NSInteger value = arc4random() % 4;
    if (value == 0) {
        picStr = [NSString stringWithFormat:@"%@hua1.png",picStr];
    }else if (value == 1){
        picStr = [NSString stringWithFormat:@"%@hua2.png",picStr];
    }else if (value == 2){
        picStr = [NSString stringWithFormat:@"%@hua3.png",picStr];
    }else if (value == 3){
        picStr = [NSString stringWithFormat:@"%@hua.png",picStr];
    }
    if (!(x % 1)) {
        NSInteger xi = arc4random() %(NSInteger)self.view.frame.size.width + 1;
        NSInteger yi = arc4random() %(NSInteger)self.view.frame.size.width + 1;
        UIImageView *image = [[[UIImageView alloc] initWithFrame:CGRectMake(xi, - 20, 100, 100)] autorelease];
        image.image = [UIImage imageNamed:picStr];
        [self.view addSubview:image];
        if (_value % 2 == 0) {
            [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                image.frame = CGRectMake(yi, self.view.frame.size.height, 100,100);
            } completion:^(BOOL finished) {
                [image removeFromSuperview];
            }];
        }else{
            [image removeFromSuperview];
        }
    }
    UIImageView *iamge = [[UIImageView alloc] initWithFrame:CGRectMake(x, - 100, 100, 100)];
    iamge.image = [UIImage imageNamed:picStr];
    [self.view addSubview:iamge];
    
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(returnAction) userInfo:nil repeats:NO];
    
    if (_value % 2 == 0 ) {
        [UIView animateWithDuration:12.0f delay:0.0f options:UIViewAnimationOptionLayoutSubviews animations:^{
            iamge.frame = CGRectMake(last, self.view.frame.size.height ,100, 100);
        } completion:^(BOOL finished) {
            [iamge removeFromSuperview];
        }];
    }else{
        
        [iamge removeFromSuperview];
    }
    
}

- (void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

- (void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}

#warning 回调
- (void)returnAction
{
    [self createImage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#warning createButton
- (void)createButton
{
    self.sum = 10;
    self.view.frame = [[UIScreen mainScreen] bounds];
    self.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
    CGFloat num = self.view.frame.size.height;
    for (int i = 0; i < num/120; i++) {
        NSInteger value = arc4random()%_sum;
        _sum--;
        NSDictionary *dic = [_coArray objectAtIndex:value];
        [_coArray removeObjectAtIndex:value];
        NSInteger x = arc4random()%(NSInteger)self.view.frame.size.width / 2 + 1;
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(- self.view.frame.size.width /2, (self.view.frame.size.height - 64) / 6 + 60 * i, self.view.frame.size.width /2, 50)];
        
        [button setBackgroundImage:[UIImage imageNamed:@"bian.png"] forState:UIControlStateNormal];
        [button setTitle:[dic objectForKey:@"title"] forState:UIControlStateNormal];
        [button setTitleColor:[WebColor deepPink] forState:UIControlStateNormal];
        
        button.tag = 10 + i;
        [button addTarget:self action:@selector(amAction:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 25;
        [self.view addSubview:button];
        [button release];
        [UIView animateWithDuration:5.0f animations:^{
            button.frame =CGRectMake(x ,(self.view.frame.size.height - 64) / 6 + 60 * i, self.view.frame.size.width /2, 50);
        }];
    }
}
- (void)amAction:(id)sender
{
    self.view.frame = [[UIScreen mainScreen] bounds];
    self.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
    UIButton *button = (UIButton *)sender;
    _buttonTag = button.tag;
    for (int i = 0; i < self.view.frame.size.height/120; i++) {
        UIButton *butt = (UIButton *)[self.view viewWithTag:10 + i];
        if (butt.frame.origin.x > self.view.frame.size.width/4) {
            [UIView animateWithDuration:1.0 animations:^{
                butt.frame = CGRectMake(self.view.frame.size.width, (self.view.frame.size.height - 64) / 6 + 60 * i, self.view.frame.size.width /2, 50);
            } completion:^(BOOL finished) {
                [butt removeFromSuperview];
                [button removeFromSuperview];
                _judge = NO;
            }];
        }else{
            [UIView animateWithDuration:1.0 animations:^{
                butt.frame = CGRectMake(- self.view.frame.size.width /2, (self.view.frame.size.height - 64) / 6 + 60 * i, self.view.frame.size.width /2, 50);
            } completion:^(BOOL finished) {
                [butt removeFromSuperview];
                [button removeFromSuperview];
                _judge = NO;
            }];
        }
    }
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(plotAction) userInfo:nil repeats:NO];
    
}
- (void)plotAction
{
    [_coArray removeAllObjects];
    [_coArray addObjectsFromArray:_buttonArray];
    NSInteger num = [self.view.subviews count];
    for (int i = 0; i < num; i++)
    {
        UIImageView *view = [self.view.subviews objectAtIndex:i];
        if (view.frame.size.height == 100) {
            view.image = [UIImage imageNamed:@""];
        }
    }
    
    UIButton *button = (UIButton *)[self.view viewWithTag:_buttonTag];
    for (NSDictionary *dic in _buttonArray) {
        NSString *str = [dic objectForKey:@"title"];
        if ([str isEqualToString:button.titleLabel.text]) {
           
            NSString *path = [dic objectForKey:@"webview_url"];
            
            HomePoltController * polt = [[HomePoltController alloc] init];
            polt.path = path;
            polt.poltTitle = [dic objectForKey:@"title"];
            [self presentViewController:polt animated:NO completion:nil];
            [polt release];
            
            
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
